package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.service.UserService;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.req.UserReq;
import com.example.req.UserSaveReq;
import com.example.resp.PageResp;
import com.example.utils.CopyUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;


    @Override
    public PageResp<User> getList(UserReq userReq) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if(!ObjectUtils.isEmpty(userReq.getName())){
            queryWrapper.eq(User::getName,userReq.getName());
        }
        if(!ObjectUtils.isEmpty(userReq.getPhone())){
            queryWrapper.eq(User::getPhone,userReq.getPhone());
        }
        if(!ObjectUtils.isEmpty(userReq.getCity())){
            queryWrapper.eq(User::getCity,userReq.getCity());
        }

        Page<User> page = new Page<>(userReq.getPage(), userReq.getSize());
        IPage<User> data = userMapper.selectPage(page, queryWrapper);

        PageResp<User> resp = new PageResp<>();
        resp.setTotal(data.getTotal());
        resp.setList(data.getRecords());
        return resp;
    }

    @Override
    public void delete(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public void save(UserSaveReq req) {
        User entity = CopyUtil.copy(req, User.class);

        if(ObjectUtils.isEmpty(req.getId())){
            userMapper.insert(entity);
        }else {
            userMapper.updateById(entity);
        }
    }




}
